// ById
function D(id) {
    return document.getElementById(id);
}

// 登录微信号
var login_robot_name = "";
// 消息记录
var global_record_data = [];
// 搜索结果消息记录
var global_record_sch_data = [];
// 获取消息记录的最小id值
var record_min_id = null;
// 联系人微信id
var contact_item_wxid = null;
// 首次加载触底
var once_load = true;
// 搜索结果首次加载触底
var sch_once_load = true;
// 消息记录来源
var record_from = "normal";
// 默认用户头像
var default_avatar = "";
// 聊天区用户头像
var contact_item_avatar = "";

window.onload = function () {
    //初始化日历选择器
    initCalendar();

    // 获取robot_name
    var robot_name = tool.getSearch("robot_name", 2);
    login_robot_name = robot_name;

    // 获取wx_id
    var wx_id = tool.getSearch("wx_id", 2);
    contact_item_wxid = wx_id;

    // 获取头像
    default_avatar = tool.storage.get("default_avatar");
    contact_item_avatar = tool.storage.get("contact_item_avatar");

    // 获取usernick
    var usernick = tool.getSearch("usernick", 2);
    D("usernick").innerHTML = "与" + usernick + "的聊天记录";

    // 获取对话聊天记录
    getChatRecord(login_robot_name, contact_item_wxid, 0);

}

//初始化日历选择器
function initCalendar() {
    laydate.render({
        elem: '#calendar-date',      //选择器
        format: 'yyyy年MM月dd日',    //日期格式
        value: new Date(),          //初始化日期 
        btns: ['now', 'confirm']    //工具按钮，默认值：['clear', 'now', 'confirm']
    });
}

// 初始化交互
function initAjax(msg) {
    var event = document.createEvent('MessageEvent');
    var origin = window.location.protocol + '//' + window.location.host;
    event.initMessageEvent('MessageReceived', true, true, msg, origin, 1234, window, null);
    document.dispatchEvent(event);
}

// 全局接收消息事件
function messageReceived(res) {
    res = Base64.decode(res);
    // alert(res)
    res = JSON.parse(res);
    if (res.code == 100) {
        var data = res.data;
        //获取用户详情
        if (res.type == "ChatRecord/GetList") {
            getChatRecordCallback(data);
        }
        //搜索聊天记录
        if (res.type == "ChatRecord/Search") {
            searchHistoryCallback(data);
        }
        //获取用户详情
        if (res.type == "Friend/Get") {
            getUserInfoCallback(data);
        }
    } else {

    }
}

// 获取对话聊天记录
function getChatRecord(robot_name, wxid, id) {
    record_from = "normal";
    var number = 20;
    var data_opt = {
        type: "ChatRecord/GetList",
        data: {
            robot_name: robot_name,
            wxid: wxid,
            id: id,
            number: number
        }
    }
    data_opt = JSON.stringify(data_opt);
    initAjax(data_opt);
}

// 获取对话聊天记录--回调
function getChatRecordCallback(data) {
    //倒序显示
    data.reverse();
    global_record_data = data.concat(global_record_data);
    // alert(JSON.stringify(data))
    if (global_record_data.length != 0) {

        if (data.length != 0) {
            //获取每次结果最小id值
            record_min_id = data[0].ID;
            for (var i = 0; i < data.length; i++) {
                if (record_min_id > data[i].ID) {
                    record_min_id = data[i].ID
                }
            }

            //显示“查看更多消息”
            D("view-more").style.display = "block";
        } else {
            //隐藏“查看更多消息”
            D("view-more").style.display = "none";
        }

        //有聊天记录,渲染
        var html = '';
        for (var i in global_record_data) {
            var item = global_record_data[i];
            html += '<div class="chat-item clearfix ' + (item.from_wxid == "localhost" ? "self" : "") + '" data-id="' + item.ID + '">';
            html += '<div class="avatar">';
            html += '<img src="' + (item.from_wxid == "localhost" ? default_avatar : contact_item_avatar) + '" data-wxid="' + item.wxid + '" onclick="viewUserDetail(this)">';
            html += '</div>';
            html += '<div class="chat-cont">';
            html += '<div class="cont">' + formatChat(item.content) + '</div>';
            html += '<div class="triangle"></div>';
            html += '<div class="msg-unsend">';
            if (item.status == 1) {
                //1:已推送给机器人，等待机器人通知
                html += '<img src="../assets/images/loading.gif" alt="">';
            } else if (item.status == -1 || item.status == -2) {
                //-1:无法推送给服务器或者机器人不在线 -2：发送失败
                html += '<img src="../assets/images/fail.svg" class="failed">';
            } else if (item.status == 9) {
                //9：成功发送用户
            }
            html += '</div>';
            html += '</div>';
            html += '</div>';
        }
        D("chat-list").innerHTML = html;
    } else {
        //隐藏“查看更多消息”
        D("view-more").style.display = "none";

        //清空聊天区内容
        D("chat-list").innerHTML = '';
    }

    //解除单次获取消息记录
    record_once_get = false;

    //聊天记录置底，显示最后一条
    if (once_load) {
        scrollToBottom();
    }

    //查看更多定位
    if (first_node_id !== null) {
        var offsetTop = document.querySelector('[data-id="' + first_node_id + '"]').offsetTop - 36;
        D("m-chat-body").scrollTop = offsetTop;
    }
}

// 查看更多消息记录
var record_once_get = false;
var sch_record_once_get = false;
var first_node_id = null;
function viewMoreRecord() {
    if (record_from == "normal") {
        //记录消息列表第一个DOM节点，用于“查看更多消息”的定位
        first_node_id = D("chat-list").firstElementChild.getAttribute("data-id");

        //取消首次加载触底
        once_load = false;
        //单次获取
        if (record_once_get) {
            return;
        }
        record_once_get = true;
        //正常记录
        getChatRecord(login_robot_name, contact_item_wxid, record_min_id);
    } else {
        //记录消息列表第一个DOM节点，用于“查看更多消息”的定位
        first_node_id = D("sch-chat-list").firstElementChild.getAttribute("data-id");

        //取消首次加载触底
        sch_once_load = false;
        //单次获取
        if (sch_record_once_get) {
            return;
        }
        sch_record_once_get = true;
        //搜索记录
        searchHistory(keywords);
    }
}

// 聊天记录默认置底，显示最后一条
function scrollToBottom() {
    var scrollHeight = D("m-chat-body").scrollHeight;
    D("m-chat-body").scrollTop = scrollHeight;
}

// 获取用户详情
function getUserInfo(wxid) {
    var data_opt = {
        type: "Friend/Get",
        data: {
            robot_name: login_robot_name,
            wxid: wxid
        }
    }
    data_opt = JSON.stringify(data_opt);

    initAjax(data_opt);
}

// 获取用户详情--回调
function getUserInfoCallback(data) {
    // alert(JSON.stringify(data))
    // var wxinfo = JSON.parse(data.wxinfo);
    var html = '';
    html += '<img src="' + data.heardpic + '" class="avatar">';
    html += '<p class="nickname">';
    html += '<span>' + data.usernick + '</span>';
    html += '<i class="icon-jslt-' + (wxinfo.Sex == 1 ? "06 male" : "07 famale") + '"></i>';
    html += '</p>';
    html += '<p class="account">账号：' + data.username + '</p>';
    html += '<div class="other">';
    html += '<p><span>签 名</span><span class="ellipsis">' + (wxinfo.Signature == "" ? "无" : wxinfo.Signature) + '</span></p>';
    html += '<p><span>地 区</span><span class="ellipsis">' + (wxinfo.Province != "" ? (wxinfo.Province + '&nbsp;&nbsp;' + wxinfo.City) : "无") + '</span></p>';
    // html += '<p><span>来 源</span><span class="ellipsis">' + data.origin + '</span></p>';
    html += '</div>';

    D("m-uinfo-main").innerHTML = html;
    D("m-uinfo-box-cover").style.display = "block";
}

// 关闭用户详情弹出框
function closeUinfoBox() {
    D("m-uinfo-box-cover").style.display = "none";
}

// 点击头像查看用户详情
function viewUserDetail(e) {
    var wx_id = e.getAttribute("data-wxid");
    getUserInfo(wx_id);

    // var url = "detail.html?robot_name=" + login_robot_name + "&wx_id=" + wx_id;
    // window.open(url);
}

// 搜索聊天记录
var searchHistory_timer = null;
var searchId = 0;
var keywords = '';
function searchHistory(val) {
    clearTimeout(searchHistory_timer);
    if (val != '') {
        searchHistory_timer = setTimeout(function () {
            record_from = "search";
            keywords = val;
            // 延时 0.3s 后开始请求
            var data_opt = {
                type: "ChatRecord/Search",
                data: {
                    robot_name: login_robot_name,
                    wxid: contact_item_wxid,
                    keyword: val,
                    id: searchId,
                    number: 20
                }
            }
            data_opt = JSON.stringify(data_opt);
            initAjax(data_opt);
        }, 300)
    } else {
        //还原
        searchId = 0;
        global_record_data = [];
        global_record_sch_data = [];
        record_from = "normal";
        once_load = true;
        sch_once_load = true;
        D("view-more").style.display = "block";

        // 获取对话聊天记录
        D("chat-list").innerHTML = '';
        getChatRecord(login_robot_name, contact_item_wxid, 0);

        //显示正常聊天记录
        D("chat-list").style.display = "block";
        D("sch-chat-list").innerHTML = '';
        D("sch-chat-list").style.display = "none";
    }
}

// 搜索聊天记录--回调
function searchHistoryCallback(data) {
    //隐藏正常聊天记录
    D("chat-list").innerHTML = '';
    D("chat-list").style.display = "none";

    //倒序显示
    data.reverse();
    global_record_sch_data = data.concat(global_record_sch_data);
    // alert(JSON.stringify(data))
    if (global_record_sch_data.length != 0) {

        if (data.length != 0) {
            //获取每次结果最小id值
            searchId = data[0].ID;
            for (var i = 0; i < data.length; i++) {
                if (searchId > data[i].ID) {
                    searchId = data[i].ID
                }
            }

            //显示“查看更多消息”
            D("view-more").style.display = "block";
        } else {
            //隐藏“查看更多消息”
            D("view-more").style.display = "none";
        }

        //有聊天记录,渲染
        var html = '';
        for (var i in global_record_sch_data) {
            var item = global_record_sch_data[i];
            html += '<div class="chat-item clearfix ' + (item.from_wxid == "localhost" ? "self" : "") + '" data-id="' + item.ID + '">';
            html += '<div class="avatar">';
            html += '<img src="' + (item.from_wxid == "localhost" ? default_avatar : contact_item_avatar) + '" data-wxid="' + item.wxid + '" onclick="viewUserDetail(this)">';
            html += '</div>';
            html += '<div class="chat-cont">';
            html += '<div class="cont">' + formatChat(item.content) + '</div>';
            html += '<div class="triangle"></div>';
            html += '<div class="msg-unsend">';
            if (item.status == 1) {
                //1:已推送给机器人，等待机器人通知
                html += '<img src="../assets/images/loading.gif" alt="">';
            } else if (item.status == -1 || item.status == -2) {
                //-1:无法推送给服务器或者机器人不在线 -2：发送失败
                html += '<img src="../assets/images/fail.svg" class="failed">';
            } else if (item.status == 9) {
                //9：成功发送用户
            }
            html += '</div>';
            html += '</div>';
            html += '</div>';
        }
        D("sch-chat-list").innerHTML = html;
        D("sch-chat-list").style.display = "block";
    } else {
        //无搜索结果
        modal.tips("无搜索结果");
    }

    //解除单次获取消息记录
    sch_record_once_get = false;

    //聊天记录置底，显示最后一条
    if (sch_once_load) {
        scrollToBottom();
    }

    //查看更多定位
    if (first_node_id !== null) {
        var offsetTop = document.querySelector('[data-id="' + first_node_id + '"]').offsetTop - 36;
        D("m-chat-body").scrollTop = offsetTop;
    }
}

// 点击图片查看大图
function viewLargePic(e) {
    var uuid = e.getAttribute("data-uuid");
    var viewer = new Viewer(document.getElementById(uuid), {
        inline: false,
        viewed() {
            viewer.zoomTo(1);
        },
    });
}

// 返回
function backTo() {
    history.go(-1);
}